/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-03-01 14:18:23
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-03-01 16:52:43
 * @FilePath: /library-web/src/src-portal/router/guard.ts
 * @Description: 路由守卫
 */
import router from '@/router';
import { useRouterStore } from '../stores/async-routers';
import { SRC_PORTAL } from '@/constants/config';
import type { RouteRecordRaw } from 'vue-router';

/**
 * @description: 生成菜单守卫
 * @return {*}
 */
export const createRouterGuard = () => {
  const routerStore = useRouterStore();
  router.beforeEach(async (to: any, from: any, next) => {
    console.log(router.getRoutes());

    console.log(to);

    let isIn = to.path.indexOf(`/${SRC_PORTAL}`) == 0;
    if (isIn) {
      if (!routerStore.routers) {
        const routers = await routerStore.generatorDynamicRouter();
        router.addRoute(routers as RouteRecordRaw);
        // 请求带有 redirect 重定向时，登录自动重定向到该地址
        const redirect = decodeURIComponent(from.query.redirect || to.path);
        if (to.path === redirect) {
          next({ ...to, replace: true });
        } else {
          next({ path: redirect });
        }
      } else {
        next();
      }
    } else {
      next();
    }
  });
};
